<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>路由</title>
    <style>
        h3 { color: red; }
        x-tab { display: block }
        .nav > li.active { background-color: red; }
        .content > li { display: none; }
        .content > li.active { display: block; }
    </style>
</head>

<body>
    <x-tab>
        <ol class="nav">
            <li class="active">
                <a href="./tab1">Nav 1</a>
            </li>
            <li>
                <a href="./tab2">Nav 2</a>
            </li>
        </ol>
        <ol class="content">
            <li class="active">Content 1</li>
            <li>Content 2</li>
        </ol>
    </x-tab>
    <a href="#top">回到顶部</a>

    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        // 页面初始加载时
        selectTab()

        // 用户点击链接时
        $('x-tab').on('click', '.nav > li > a', (event) => {
            event.preventDefault()
            let url = event.currentTarget.getAttribute('href')
            window.history.pushState(null, null, url)
            selectTab()
        })

        // 工具函数
        function selectTab() {
            let index = window.location.pathname.substring(4) - 1 || '0'
            $('x-tab > .nav > li').eq(index).addClass('active')
                .siblings().removeClass('active')
            $('x-tab > .content > li').eq(index).addClass('active')
                .siblings().removeClass('active')
        }
    </script>
</body>

</html>